<%@ Page Language="C#" MasterPageFile="~/Site.master" Title="GridView with ACT MaskEdit and Calendar" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server">
    <link href="../Act/Resources/Calendar.css" rel="stylesheet" type="text/css" />
    <asp:ScriptManagerProxy ID="TheScriptManager" runat="server">
        <Scripts>
            <asp:ScriptReference Path="~/Act/Scripts/Common.js" />
            <asp:ScriptReference Path="~/Act/Scripts/BaseScripts.js" />
            <asp:ScriptReference Path="~/Act/Scripts/Timer.js" />
            <asp:ScriptReference Path="~/Act/Scripts/MaskedEditValidator.js" />
            <asp:ScriptReference Path="~/Act/Scripts/MaskedEditBehavior.js" />
            <asp:ScriptReference Path="~/Act/Scripts/DateTime.js" />
            <asp:ScriptReference Path="~/Act/Scripts/Animations.js" />
            <asp:ScriptReference Path="~/Act/Scripts/AnimationBehavior.js" />
            <asp:ScriptReference Path="~/Act/Scripts/PopupBehavior.js" />
            <asp:ScriptReference Path="~/Act/Scripts/Threading.js" />
            <asp:ScriptReference Path="~/Act/Scripts/CalendarBehavior.js" />
        </Scripts>
    </asp:ScriptManagerProxy>
    <h3>ACT MaskEdit and Calendar</h3>
    <table>
        <tr>
            <td style="text-align:left">
                <AjaxData:GridView ID="GridView1" runat="server" CssClass="DataWebControlStyle" CellSpacing="0" CellPadding="3" DataKeyName="ID" SortColumn="FirstName" SortOrderAscendingImageUrl="~/Images/up.gif" SortOrderDescendingImageUrl="~/Images/dn.gif" SortCommandEvent="onSortCommand" RowCreatedEvent="onRowCreated" RowDataBoundEvent="onRowDataBound" EditCommandEvent="onEditCommand" UpdateCommandEvent="onUpdateCommand" CancelCommandEvent="onCancelCommand">
                   <AlternatingRowStyle CssClass="AlternatingRowStyle" />
                   <RowStyle CssClass="RowStyle"/>
                   <HeaderStyle CssClass="HeaderStyle"/>
                   <Columns>
                        <AjaxData:GridViewCommandColumn ButtonType="Image" ShowEditButton="true" ShowDeleteButton="false" ShowCancelButton="true" EditImageUrl="~/Images/edit.gif" DeleteImageUrl="~/Images/delete.gif" UpdateImageUrl="~/Images/update.gif" CancelImageUrl="~/Images/cancel.gif" HeaderStyle-Wrap="false" ItemStyle-Wrap="false"/>
                        <AjaxData:GridViewBoundColumn HeaderText="First Name" DataField="FirstName" SortField="FirstName" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" HeaderStyle-Wrap="false"/>
                        <AjaxData:GridViewBoundColumn HeaderText="Last Name" DataField="LastName" SortField="LastName" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" HeaderStyle-Wrap="false"/>
                        <AjaxData:GridViewTemplateColumn HeaderText="Birth Date" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="right" HeaderStyle-Wrap="false" ItemStyle-Wrap="false">
                            <ItemTemplate>
                                <span id="spnBirthDate"></span>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <input type="text" id="txtBirthDate" />
                                <input type="image" id="btnCalendar" alt="Calendar" src="Images/calendar.gif" onclick="return false;" />
                            </EditItemTemplate>
                        </AjaxData:GridViewTemplateColumn>
                        <AjaxData:GridViewBoundColumn HeaderText="Phone" DataField="Phone" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" HeaderStyle-Wrap="false"/>
                   </Columns>
                </AjaxData:GridView>
            </td>
        </tr>
        <tr>
            <td style="text-align:right">
                <AjaxData:Pager ID="Pager1" runat="server" CssClass="PagerRowStyle" CurrentPageStyle-CssClass="PagerCurrentPage" OtherPageStyle-CssClass="PagerOtherPage" PageChangedEvent="pageChanged"></AjaxData:Pager>
            </td>
        </tr>
    </table>
    <script type="text/javascript">

        AjaxControlToolkit.Resources=   {
                                            "Shared_BrowserSecurityPreventsPaste":"Your browser security settings don\u0027t permit the automatic execution of paste operations. Please use the keyboard shortcut Ctrl+V instead.",
                                            "Calendar_Today":"Today: {0}",
                                            "Common_DateTime_InvalidFormat":"Invalid format"
                                        };

        var _gridView;
        var _pager;

        var _employees;

        function pageLoad(sender, e)
        {
            _gridView = GridView1;
            _pager = Pager1;
            loadEmployees();
        }

        function loadEmployees()
        {
            //Need to convert the sortoder so our WS understand
            var sortColumn = _gridView.get_sortColumn();
            var sortOrder = (_gridView.get_sortOrder() == AjaxDataControls.GridViewSortOrder.Descending) ? 'DESC' : 'ASC';
            var startIndex = (_pager.get_pageIndex() * _pager.get_pageSize());
            DataService.GetEmployeeList(startIndex, _pager.get_pageSize(), sortColumn, sortOrder, onLoadSuccess);
        }

        function onLoadSuccess(result)
        {
            _employees = result.Rows;
            _pager.set_recordCount(result.Total);
            bindEmployees();
        }

        function bindEmployees()
        {
            _gridView.set_dataSource(_employees);
            _gridView.dataBind();
        }

        function onSortCommand(sender, e)
        {
            _gridView.set_sortColumn(e.get_sortColumn())
            _gridView.set_sortOrder(e.get_sortOrder());
            _pager.set_pageIndex(0); // need to reset the current page as sorting is changed
            _gridView.set_editIndex(-1);
            loadEmployees();
        }

        function onRowCreated(sender, e)
        {
            var row = e.get_row();

            if (row.get_rowType() == AjaxDataControls.GridViewRowType.EditRow)
            {
                //Now we are in Edit mode, lets attach the Extenders.

                var txtBirthDate = row.findControl('txtBirthDate');
                var btnCalendar = row.findControl('btnCalendar');

                var maskExtenderID = txtBirthDate.id + 'MaskExtender';
                var calendarExtenderID = txtBirthDate.id + 'CalendarExtender';

                var maskExtender = $find(maskExtenderID);

                if (maskExtender)
                {
                    //There is a previous instance so we need to remove it.
                    Sys.Application.removeComponent(maskExtender);
                }

                var calendarExtender = $find(calendarExtenderID);

                if (calendarExtender)
                {
                    //There is a previous instance so we need to remove it.
                    Sys.Application.removeComponent(calendarExtender);
                }

                //Now create the extender in the client Side
                $create(AjaxControlToolkit.MaskedEditBehavior, {'CultureAMPMPlaceholder':'AM;PM', 'CultureDateFormat':'DMY', 'CultureDatePlaceholder': '/', 'CultureTimePlaceholder':':', 'Mask':'99/99/9999', 'MaskType':1, 'ClearMaskOnLostFocus':false, 'id':maskExtenderID}, null, null, txtBirthDate);
                $create(AjaxControlToolkit.CalendarBehavior, {'button':btnCalendar, 'id':calendarExtenderID}, null, null, txtBirthDate);
            }
        }

        function onRowDataBound(sender, e)
        {
            var row = e.get_row();

            if (row.get_isDataRowType())
            {
                var employee = row.get_dataItem();

                var formattedBirthDate = employee.BirthDate.format('d');

                if (row.get_rowType() == AjaxDataControls.GridViewRowType.EditRow)
                {
                    var txtBirthDate = row.findControl('txtBirthDate');
                    txtBirthDate.value = formattedBirthDate;
                }
                else
                {
                    var spnBirthDate = row.findControl('spnBirthDate');
                    setText(spnBirthDate, formattedBirthDate);
                }
            }
        }

        function onEditCommand(sender, e)
        {
            _gridView.set_editIndex(e.get_row().get_rowIndex());
        }

        function onUpdateCommand(sender, e)
        {
            var row = e.get_row();
            var employeeId = _gridView.get_dataKeys()[e.get_row().get_rowIndex()];

            //Since we support drag and drop the column index may vary, so get the current index first.

            var lastNameColumnIndex = _gridView.getColumnIndexByHeaderText('Last Name');
            var firstNameColumnIndex = _gridView.getColumnIndexByHeaderText('First Name');
            var birthDateColumnIndex = _gridView.getColumnIndexByHeaderText('Birth Date');
            var phoneColumnIndex = _gridView.getColumnIndexByHeaderText('Phone');

            var txtLastName = row.get_container().childNodes[lastNameColumnIndex].childNodes[0];
            var txtFirstName = row.get_container().childNodes[firstNameColumnIndex].childNodes[0];
            var txtBirthDate = row.get_container().childNodes[birthDateColumnIndex].childNodes[0];
            var txtPhone = row.get_container().childNodes[phoneColumnIndex].childNodes[0];

            var employee = e.get_row().get_dataItem();

            employee.LastName = txtLastName.value.trim();
            employee.FirstName = txtFirstName.value.trim();
            employee.BirthDate = Date.parseLocale(txtBirthDate.value.trim());
            employee.Phone = txtPhone.value.trim();

            DataService.UpdateEmployee(
                                        employeeId,
                                        employee.LastName,
                                        employee.FirstName,
                                        employee.BirthDate,
                                        employee.Phone,
                                        function(result)
                                        {
                                            if (result == true)
                                            {
                                                _gridView.set_editIndex(-1);
                                            }
                                        }
                                      );
        }

        function onCancelCommand(sender, e)
        {
            _gridView.set_editIndex(-1);
        }

        function pageChanged(sender, e)
        {
            _pager.set_pageIndex(e.get_newPageIndex());
            _gridView.set_editIndex(-1);
            loadEmployees();
        }

        function setText(element, text)
        {
            if (typeof element.textContent != 'undefined')
            {
                element.textContent = text;
            }
            else if (typeof element.innerText != 'undefined')
            {
                element.innerText = text;
            }
        }

    </script>
</asp:Content>